<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];

    require_once($rootDir.'/functions.php');
    require_once($rootDir.'/classes/LeproBJAppSettings.class.php');
    require_once($rootDir.'/classes/LeproHelper.class.php');
	require_once($rootDir.'/classes/SessionManager.class.php');
	require_once($rootDir.'/classes/Card.class.php');

    class UserStatsImageGenerator {
    	
    	private static $CACHE_DIR = '/img/usrimgcache/';    	
    	private static $FILE_PREFIX = 'ustats_';
    	private static $FILE_EXT = '.png';
    	
    	private static function getUserImgFilePath($userId) {    		
    		return self::$CACHE_DIR.self::$FILE_PREFIX.$userId.self::$FILE_EXT;    		
    	}
    	
        public static function getImage($userId) {
            
        	$filePath = $_SERVER['DOCUMENT_ROOT'].self::getUserImgFilePath($userId);
        	
        	clearstatcache();
            if (file_exists($filePath)) {
            	
            	/* Header( "HTTP/1.1 301 Moved Permanently" ); */ 
            	// header('Location: http://'.$_SERVER['HTTP_HOST'].$filePath);
            	
                /* header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 */
                /* header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past */
            	
            	header('Content-type: image/png');
                readfile($filePath);
            	
            } else return false;
            
        }
    	
    	public static function isImgUpToDate($userId) {
    		
    		clearstatcache();
    		return file_exists($_SERVER['DOCUMENT_ROOT'].self::getUserImgFilePath($userId));
    		
    	}
    	
    	public static function generateImage($user, $userPos) {
    		
    		$rootDir = $_SERVER['DOCUMENT_ROOT']; 
                
            $font = $rootDir.'/'.LeproBJAppSettings::$PROFILE_IMGS_FONT;
            $symbolfont = $rootDir.'/'.LeproBJAppSettings::$PROFILE_IMGS_SYMBFONT;

            $width = LeproBJAppSettings::$PROFILE_IMGS_WIDTH;
            $height = LeproBJAppSettings::$PROFILE_IMGS_HEIGHT;
                
            $fontSize = LeproBJAppSettings::$PROFILE_IMGS_FONTSIZE;

            $im = imagecreate($width, $height);
            $bg = imagecolorallocate($im, 0xff, 0xff, 0xff);
            $black = imagecolorallocate($im, 0, 0, 0);
            $grey = imagecolorallocate($im, 0xaa, 0xaa, 0xaa);
            $red = imagecolorallocate($im, 0x99, 0, 0);
            $blue = imagecolorallocate($im, 0, 0, 0x99);
            $green = imagecolorallocate($im, 0, 0x99, 0);
            $darkblue = imagecolorallocate($im, 0x00, 0x00, 0x33);
            $darkgreen = imagecolorallocate($im, 0x33, 0x66, 0x33);
            $defaultColor = $black;
            imagerectangle($im,0, 0, $width-1, $height-1, $grey);

            $username = $user->getUsername();
            $userId = $user->getID();
            $userIdText = ($userId > LeproHelper::$DIRTY_OFFSET) ? '.'.($userId - LeproHelper::$DIRTY_OFFSET) : $userId; 
            $cardId = $user->getCardID();
            $cardName = Card::getCardName($cardId);
            $cardText = Card::getCardHTMLCode($cardId, false, true);
            $userScore = $user->getGScore();
            $scoreText = sprintf('%.2f', $userScore);
            $unameColor = $darkgreen;
            $cardColor = Card::getCardColor($cardId) ? $red : $darkblue;
            $posColor = ($userPos <= 10) ? $green : (($userPos <= 50) ? $blue : ($userPos <= 100) ? $darkblue : $grey);
            $posSize = ($userPos < 10) ? 11 : (($userPos < 100) ? 10 : ($userPos < 1000) ? 9 : 8);
            $scoreColor = ($userScore > 0) ? $green : (($userScore == 0) ? $blue : $grey);
            $scoreSize = ($userScore >= 10) ? 8 : (($userScore >= 0) ? 9 : 7);
            // $userText = 'Юзернейм '.$username.' ['.$userIdText.'] играет в Лепро&#8211;Блекджек, там он заработал '.$scoreText.' очков (имеет на руках карту '.$cardName.') и занимает '.$positionText.'-е место в рейтинге юзернеймов.';
            $userText = 'Юзернейм <0>'.$username.' ['.$userIdText.']</0> играет в Лепро&#8211;Блекджек,'.
                                ' там он заработал <1>'.$scoreText.'</1> очков (имеет на руках карту <2>'.
            $cardName.'</2>) и занимает <3>'.$userPos.'</3>-е место в рейтинге юзернеймов.';
            $linkText = 'http://blackjack.crzcrz.net';
                
            imagettftextcoloredwrap($im, $fontSize, 0, 50, 20, $width - 55, array($unameColor, $scoreColor, $cardColor, $posColor), $font, $userText, $defaultColor, true);
            // imagettftextwrap($im, $fontSize, 0, 50, 20, $width - 55, $black, $font, $userText);
            imagettftext($im, $fontSize, 0, 10, 20, $cardColor, $symbolfont, $cardText);
            imagettftext($im, $posSize, 0, 10, 37, $posColor, $symbolfont, $userPos);
            imagettftext($im, $scoreSize, 0, 10, 52, $scoreColor, $symbolfont, $scoreText);
            imagettftext($im, 7, 0, 10, 90, $blue, $symbolfont, $linkText);

            header('Content-type: image/png');
                
            imagepng($im);
            imagepng($im, $_SERVER['DOCUMENT_ROOT'].self::getUserImgFilePath($userId));
            
            imagedestroy($im);

            // SessionManager::registerVar($TIME_VAR_NAME, microtime(true));
    		
    	}
    	
    	public static function invalidateImage($userId) {
    		
    		/*
    		 // remove single file
    		 $fileFullPath = $_SERVER['DOCUMENT_ROOT'].self::getUserImgFilePath($userId);
    		
    		 clearstatcache();
    		 if (file_exists($fileFullPath)) unlink($fileFullPath);
            */
    		
    		unlinkRecursive($_SERVER['DOCUMENT_ROOT'].self::$CACHE_DIR);
    		
    	}
    	
    }

?>